<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title></title>
</head>
<body>
	<input type="text" name="" value="青岛">
	<button>查询</button>
     <img src="">
	<ul></ul>
	<script type="text/javascript" src="ajax.js"></script>
	<script type="text/javascript">
		let btn = document.querySelector("button")
		let inp = document.querySelector("input")
		let img = document.querySelector("img")
		let ul = document.querySelector("ul")
		// 用promuse封装一下天气接口
		function weaPro(url){
			return new Promise((resolve, reject) => {
				let xhr = new XMLHttpRequest()
				xhr.open("get", url)
				xhr.send()
				xhr.onreadystatechange = function(){
					if (xhr.readyState == 4) {
						let res = JSON.parse(xhr.responseText)
						if (res.code == 200){
							resolve(res)
						}else{
							reject(res)
						}
					}
				}
			})

			
		}

		btn.onclick = function() {

			weaPro(`https://geoapi.qweather.com/v2/city/lookup?location=${inp.value}&key=c494e264764449f7b4f6bf742276d7f9`).then((res) => {
				console.log(res)
				let newUrl = `https://devapi.qweather.com/v7/weather/now?location=${res.location[0].id}&key=c494e264764449f7b4f6bf742276d7f9`
				return weaPro(newUrl)
			})
			.then((res) => {
				img.src = `https://a.hecdn.net/img/common/icon/202106d/${res.now.icon}.png`
				ul.innerHTML = ""
				let li = `<li>温度:${res.now.temp}℃ 天气:${res.now.text} 风向:${res.now.windDir}</li>`
				ul.innerHTML += li
			})
			.catch((err) => {
				alert("天气查询失败")
			})
		}

		ajax({
			method:"get",
			url: "https://geoapi.qweather.com/v2/city/lookup",
			params:{
				location: inp.value,
				key: "c494e264764449f7b4f6bf742276d7f9"
			}

		}).then(res => {
			console.log(res, "========")
		})
	</script>
</body>
</html>